//
//  BlurEffectMenu.m
//  EPTool
//
//  Created by guoshiqing on 2018/5/2.
//  Copyright © 2017年 云数动能. All rights reserved.
//

#import "BlurEffectMenu.h"
#import "Macro.h"
#import "NSDate+Extend.h"
#import "GlobalUtil.h"
#import "UserSettings.h"
#import "UIView+DDAddition.h"

#define IPHONEX_FIX ((812.0 == [[UIScreen mainScreen] bounds].size.height)?83:49)
#define LeftX 27.f

@implementation BlurEffectMenuItem

@end


@interface BlurEffectMenu ()
@property (nonatomic, assign) NSUInteger colNumber;
@property (nonatomic, assign) BOOL isShow;

@property (nonatomic, strong) UIView *viwDate;

// 天气
@property (nonatomic, strong) UIImageView *igvCode;
@property (nonatomic, strong) UILabel *lblTmp;
@property (nonatomic, strong) UILabel *lblCity;
@property (nonatomic, strong) UILabel *lblSubLocal;

@end

@implementation BlurEffectMenu

- (instancetype)initWithMenus:(NSArray *)menus withColNumber:(NSUInteger)colNumber isShowDate:(BOOL)isShow{
    self = [super init];
    if (self) {
        self.menuItemArr = menus;
        self.colNumber = (0 == colNumber)?1:colNumber;
        self.isShow = isShow;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor clearColor]];
    
    //手势
    [self gesture];
    
    //布局View
    [self setUpView];
}

- (void)gesture{
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapOnBackground)]];
    
    UISwipeGestureRecognizer *swipeGesture=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(didTapOnBackground)];
    [swipeGesture setDirection:UISwipeGestureRecognizerDirectionUp];
    [self.view addGestureRecognizer:swipeGesture];
}

#pragma mark - setUpView
- (void)setUpView{
    
    //毛玻璃
    UIBlurEffect *blurEffect=[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *visualEffectView=[[UIVisualEffectView alloc] initWithEffect:blurEffect];
    [visualEffectView setFrame:self.view.bounds];
    visualEffectView.alpha = 1.0;
    [self.view addSubview:visualEffectView];
    
    // 显示日期
    if (self.isShow) [self addDateView];
    // 显示天气
    if (UserSaveInfo.currentCity.length > 0) {
        [self addWeather];
    } else {
        [self addNoWeather];
    }
    
    //4列
    NSInteger totalloc = self.colNumber;
    NSInteger rowCount = (0 == self.menuItemArr.count%self.colNumber)?self.menuItemArr.count/self.colNumber:(self.menuItemArr.count/self.colNumber+1);
    CGFloat appvieww = 60;
    CGFloat appviewh = 60;
    CGFloat margin = (self.view.frame.size.width-totalloc*appvieww)/(totalloc+1);
    
    for (NSInteger i = 0; i < self.menuItemArr.count; i++) {
        
        NSInteger row = i/totalloc;//行号
        NSInteger loc = i%totalloc;//列号
        CGFloat appviewx = margin + (margin + appvieww)*loc;
        CGFloat appviewy = ((self.view.frame.size.height - IPHONEX_FIX - 94)  - rowCount*84) + (56 + appviewh)*row;
        
        //button
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setFrame:CGRectMake(appviewx, UI_SCREEN_HEIGHT+100, appvieww, appviewh)];
        [button setTag:i];
        [button addTarget:self action:@selector(itemBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        
        //label
        UILabel *label = [[UILabel alloc]init];
        [label setFrame:CGRectMake(appviewx, button.frame.origin.y+button.bounds.size.height+7, appvieww, 17)];
        [label setTextColor:[EPColor epColor_Nav]];
        [label setFont:[UIFont systemFontOfSize:12.0]];
        [label setTextAlignment:NSTextAlignmentCenter];
        [label setTag:i];
        [self.view addSubview:label];
        
        BlurEffectMenuItem *item = self.menuItemArr[i];
        [button setImage:item.icon forState:UIControlStateNormal];
        [label setText:item.title];
        
        // 入场动效
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05*NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:1.f delay:(0.2-0.02*i) usingSpringWithDamping:1.0f initialSpringVelocity:15.0f options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
                button.frame = CGRectMake(appviewx, appviewy, appvieww,appviewh);
                [label setFrame:CGRectMake(appviewx, button.frame.origin.y+button.bounds.size.height+5, appvieww, 25)];
            } completion:^(BOOL finished) {
            }];
        });
    }
}

#pragma mark - 添加日期显示
- (UIView *)viwDate
{
    if (!_viwDate) {
        _viwDate = [[UIView alloc] initWithFrame:CGRectMake(LeftX, 116.0f, UI_SCREEN_WIDTH - 2*LeftX, 82.0f)];
    }
    return _viwDate;
}

- (void)addDateView
{
    [self.view addSubview:self.viwDate];
    
    NSDate *nowDate = [NSDate date];
    
    // 显示当月的日期
    UILabel *lblDay = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60.0f, 56.0f)];
    lblDay.textAlignment = NSTextAlignmentLeft;
    lblDay.font = SystemFont(48.0f);
    lblDay.textColor = [EPColor epColor_Nav];
    [self.viwDate addSubview:lblDay];
    lblDay.text = [nowDate getDayString];
    // 显示名言
    UILabel *lblWord = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(lblDay.frame)+6.0f, UI_SCREEN_WIDTH - 2*LeftX, 20.0f)];
    lblWord.textAlignment = NSTextAlignmentLeft;
    lblWord.font = SystemFont(14.0f);
    lblWord.textColor = [EPColor epColor_Nav];
    [self.viwDate addSubview:lblWord];
    lblWord.text = UserSaveInfo.wisdom;
    lblWord.numberOfLines = 0;
    CGSize wordSize = [GlobalUtil sizeFortext:UserSaveInfo.wisdom withFont:SystemFont(14.0f) constrainedToSize:CGSizeMake(UI_SCREEN_WIDTH - 2*LeftX, 100.0f)];
    lblWord.height = wordSize.height;
    // 显示星期几
    UILabel *lblWeek = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(lblDay.frame), 7.0f, 60.0f, 20.0f)];
    lblWeek.textAlignment = NSTextAlignmentLeft;
    lblWeek.font = SystemFont(14.0f);
    lblWeek.textColor = [EPColor epColor_Nav];
    [self.viwDate addSubview:lblWeek];
    lblWeek.text = [NSDate getTodayWeekday];
    // 显示年/月
    UILabel *lblDate  = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(lblWeek.frame), CGRectGetMaxY(lblWeek.frame)+2.f, 60.0f, 20.0f)];
    lblDate.textAlignment = NSTextAlignmentLeft;
    lblDate.font = SystemFont(14.0f);
    lblDate.textColor = [EPColor epColor_Nav];
    [self.viwDate addSubview:lblDate];
    lblDate.text = [NSString stringWithFormat:@"%02ld/%ld", [nowDate getMonth], [nowDate getYear]];
}

- (void)addWeather
{
    NSString *tmp = UserSaveInfo.weatherTmp.length > 0 ? [NSString stringWithFormat:@"%@°", UserSaveInfo.weatherTmp] : @"";
    UILabel *lblTmp = [[UILabel alloc] initWithFrame:CGRectMake(0.f, 7.f, 75.f, 20.0f)];
    lblTmp.textColor = [EPColor epColor_Nav];
    lblTmp.font = SystemFont(24.0f);
    lblTmp.text = tmp;
    [self.viwDate addSubview:lblTmp];
    
    NSString *cityAndLocal = [NSString stringWithFormat:@"%@ %@", UserSaveInfo.currentCity, UserSaveInfo.currentSubLocal];
    NSString *cityStr = UserSaveInfo.currentCity;
    UILabel *lblSubLocal = [[UILabel alloc] initWithFrame:CGRectMake(0.f, CGRectGetMaxY(lblTmp.frame)+2.f, 75.f, 20.0f)];
    lblSubLocal.textColor = [EPColor epColor_Nav];
    lblSubLocal.font = SystemFont(14.0f);
    lblSubLocal.text = cityStr;
    [self.viwDate addSubview:lblSubLocal];
    CGSize cityAndLocalSize = [GlobalUtil sizeFortext:cityAndLocal withFont:SystemFont(14.0f) constrainedToSize:CGSizeMake(Cell_W, 20.f)];
    CGSize localSize = [GlobalUtil sizeFortext:cityStr withFont:SystemFont(14.0f) constrainedToSize:CGSizeMake(Cell_W, 20.f)];
    CGFloat halfWidth = (UI_SCREEN_WIDTH - 2 * LeftX) / 2;
    if (cityAndLocalSize.width > halfWidth) {
        lblSubLocal.text = cityStr;
        lblSubLocal.width = localSize.width > halfWidth ? halfWidth : localSize.width;
    } else {
        lblSubLocal.text = cityAndLocal;
        lblSubLocal.width = cityAndLocalSize.width;
    }
    lblTmp.width = lblSubLocal.width;
    lblSubLocal.right = self.viwDate.width;
    lblTmp.right = self.viwDate.width;
    
    UIImageView *weather = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40.f, 40.f)];
    NSString *codeImg = [NSString stringWithFormat:@"weather_%@", UserSaveInfo.weatherCode];
    weather.image = [UIImage imageNamed:codeImg];
    [self.viwDate addSubview:weather];
    weather.top = 8.f;
    weather.right = lblTmp.left - 5.0f;
}

- (void)addNoWeather
{
    UIImageView *noWeather = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 56.f, 56.f)];
    noWeather.image = [UIImage imageNamed:@"weather_Location"];
    [self.viwDate addSubview:noWeather];
    noWeather.right = self.viwDate.width;
}

#pragma mark - Event
- (void)didTapOnBackground{
    //点击空白处，dismiss
    [self customAnimation];
    WEAKSELF
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3*NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(blurEffectMenuDidTapOnBackground:)]) {
            [weakSelf.delegate blurEffectMenuDidTapOnBackground:weakSelf];
        }
    });
}

- (void)itemBtnClicked:(UIButton *)sender{
    //点击按钮缩放代码
    [UIView animateWithDuration:0.25 animations:^{
        sender.transform=CGAffineTransformMakeScale(1.7,1.7);
    }];
    //button dismiss动画  Spring Animation
    [self customAnimation];
    WEAKSELF
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3*NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(blurEffectMenu:didTapOnItem:)]) {
            [weakSelf.delegate blurEffectMenu:weakSelf didTapOnItem:weakSelf.menuItemArr[sender.tag]];
        }
    });
}

#pragma mark - UIView animation
// 出场动效
- (void)customAnimation{
    for (UIView *view in self.view.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *btn=(UIButton *)view;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05*NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
                //UIView animate动画:弹出添加按钮,从顶部弹到指定位置
                [UIView animateWithDuration:1.0f delay:0.02*(btn.tag) usingSpringWithDamping:0.6f initialSpringVelocity:1.5f options:UIViewAnimationOptionCurveEaseInOut animations:^{
                    btn.frame = CGRectMake(btn.frame.origin.x, UI_SCREEN_HEIGHT+100, btn.frame.size.width,btn.frame.size.height);
                } completion:^(BOOL finished) {
                }];
            });
        }
        if ([view isKindOfClass:[UILabel class]]) {
            UILabel *label=(UILabel *)view;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05*NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
                //UIView animate动画:弹出添加按钮,从顶部弹到指定位置
                [UIView animateWithDuration:1.0f delay:0.02*(label.tag) usingSpringWithDamping:0.6f initialSpringVelocity:1.5f options:UIViewAnimationOptionCurveEaseInOut animations:^{
                    [label setTextColor:[UIColor clearColor]];
                } completion:^(BOOL finished) {
                }];
            });
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
